import React, { useState } from 'react';
import { Button, Modal, List, Tag, Typography, Empty, Space, Input, Checkbox } from 'antd';
import { PlusOutlined, DatabaseOutlined, SearchOutlined, CheckCircleFilled } from '@ant-design/icons';
import { KnowledgeBase } from '../types';
import { useTranslation } from 'react-i18next';

const { Text } = Typography;
const { Search } = Input;

interface KnowledgeBaseSelectorProps {
  knowledgeBases: KnowledgeBase[];
  value?: number[];
  onChange?: (selectedIds: number[]) => void;
}

const KnowledgeBaseSelector: React.FC<KnowledgeBaseSelectorProps> = ({ 
  knowledgeBases, 
  value = [], 
  onChange 
}) => {
  const { t } = useTranslation();
  const [modalVisible, setModalVisible] = useState(false);
  const [searchText, setSearchText] = useState('');
  const [tempSelected, setTempSelected] = useState<number[]>(value);

  const selectedKBs = knowledgeBases.filter(kb => value.includes(kb.id));
  
  const filteredKBs = knowledgeBases.filter(kb => 
    kb.name.toLowerCase().includes(searchText.toLowerCase()) ||
    (kb.description && kb.description.toLowerCase().includes(searchText.toLowerCase()))
  );

  const handleOpenModal = () => {
    setTempSelected(value);
    setSearchText('');
    setModalVisible(true);
  };

  const handleConfirm = () => {
    onChange?.(tempSelected);
    setModalVisible(false);
  };

  const handleCancel = () => {
    setTempSelected(value);
    setModalVisible(false);
  };

  const handleToggleKB = (kbId: number) => {
    if (tempSelected.includes(kbId)) {
      setTempSelected(tempSelected.filter(id => id !== kbId));
    } else {
      setTempSelected([...tempSelected, kbId]);
    }
  };

  const handleRemoveKB = (kbId: number) => {
    onChange?.(value.filter(id => id !== kbId));
  };

  return (
    <div>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <Text type="secondary">
            {selectedKBs.length > 0 
              ? `${t('agent.selectedKBs')}: ${selectedKBs.length}`
              : t('agent.noKBsSelected')}
          </Text>
          <Button type="primary" onClick={handleOpenModal} icon={<PlusOutlined />}>
            {t('agent.selectKnowledgeBases')}
          </Button>
        </div>

        {selectedKBs.length === 0 ? (
          <Empty
            image={Empty.PRESENTED_IMAGE_SIMPLE}
            description={t('agent.noKBsSelectedDescription')}
            style={{ padding: '40px 0' }}
          />
        ) : (
          <List
            bordered
            dataSource={selectedKBs}
            renderItem={(kb) => (
              <List.Item
                style={{ 
                  padding: '16px 24px',
                  transition: 'background-color 0.3s',
                }}
                actions={[
                  <Button
                    key="remove"
                    type="text"
                    danger
                    size="small"
                    onClick={() => handleRemoveKB(kb.id)}
                  >
                    {t('common.remove')}
                  </Button>,
                ]}
              >
                <List.Item.Meta
                  avatar={
                    <div
                      style={{
                        width: 40,
                        height: 40,
                        borderRadius: '8px',
                        backgroundColor: '#1890ff',
                        display: 'flex',
                        alignItems: 'center',
                        justifyContent: 'center',
                        color: '#fff',
                        fontSize: '18px',
                      }}
                    >
                      <DatabaseOutlined />
                    </div>
                  }
                  title={
                    <Space size="middle">
                      <Text strong style={{ fontSize: '16px' }}>
                        {kb.name}
                      </Text>
                      {kb.is_public && (
                        <Tag color="green">{t('knowledgeBase.public')}</Tag>
                      )}
                    </Space>
                  }
                  description={
                    kb.description && (
                      <Text type="secondary" style={{ fontSize: '13px' }}>
                        {kb.description}
                      </Text>
                    )
                  }
                />
              </List.Item>
            )}
          />
        )}
      </Space>

      <Modal
        title={t('agent.selectKnowledgeBases')}
        open={modalVisible}
        onOk={handleConfirm}
        onCancel={handleCancel}
        width={700}
        okText={t('common.confirm')}
        cancelText={t('common.cancel')}
      >
        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
          <Search
            placeholder={t('agent.searchKnowledgeBases')}
            prefix={<SearchOutlined />}
            allowClear
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
          />

          <div style={{ 
            maxHeight: '500px', 
            overflowY: 'auto',
            border: '1px solid #f0f0f0',
            borderRadius: '8px',
          }}>
            {filteredKBs.length === 0 ? (
              <Empty
                image={Empty.PRESENTED_IMAGE_SIMPLE}
                description={t('agent.noKBsFound')}
                style={{ padding: '40px 0' }}
              />
            ) : (
              <List
                dataSource={filteredKBs}
                renderItem={(kb) => {
                  const isSelected = tempSelected.includes(kb.id);
                  return (
                    <List.Item
                      style={{ 
                        padding: '16px 24px',
                        cursor: 'pointer',
                        transition: 'background-color 0.3s',
                        backgroundColor: isSelected ? '#e6f7ff' : 'transparent',
                      }}
                      onMouseEnter={(e) => {
                        if (!isSelected) {
                          e.currentTarget.style.backgroundColor = '#fafafa';
                        }
                      }}
                      onMouseLeave={(e) => {
                        e.currentTarget.style.backgroundColor = isSelected ? '#e6f7ff' : 'transparent';
                      }}
                      onClick={() => handleToggleKB(kb.id)}
                    >
                      <List.Item.Meta
                        avatar={
                          <div
                            style={{
                              width: 40,
                              height: 40,
                              borderRadius: '8px',
                              backgroundColor: isSelected ? '#1890ff' : '#d9d9d9',
                              display: 'flex',
                              alignItems: 'center',
                              justifyContent: 'center',
                              color: '#fff',
                              fontSize: '18px',
                              transition: 'background-color 0.3s',
                            }}
                          >
                            {isSelected ? <CheckCircleFilled /> : <DatabaseOutlined />}
                          </div>
                        }
                        title={
                          <Space size="middle">
                            <Text strong style={{ fontSize: '16px' }}>
                              {kb.name}
                            </Text>
                            {kb.is_public && (
                              <Tag color="green">{t('knowledgeBase.public')}</Tag>
                            )}
                            {isSelected && (
                              <Tag color="blue">{t('agent.selected')}</Tag>
                            )}
                          </Space>
                        }
                        description={
                          kb.description && (
                            <Text type="secondary" style={{ fontSize: '13px' }}>
                              {kb.description}
                            </Text>
                          )
                        }
                      />
                      <Checkbox 
                        checked={isSelected}
                        onClick={(e) => e.stopPropagation()}
                        onChange={() => handleToggleKB(kb.id)}
                      />
                    </List.Item>
                  );
                }}
              />
            )}
          </div>

          <div style={{ 
            padding: '12px', 
            backgroundColor: '#f5f5f5', 
            borderRadius: '4px',
            textAlign: 'center',
          }}>
            <Text type="secondary">
              {t('agent.selectedCount', { count: tempSelected.length, total: knowledgeBases.length })}
            </Text>
          </div>
        </Space>
      </Modal>
    </div>
  );
};

export default KnowledgeBaseSelector;

